<?php

namespace hiduoke\services\douyinMinApp\API;

use hiduoke\services\douyinMinApp\utils\AesEncryptUtil;

class DouyinOpenApi extends BaseApi
{
    // 第三方小程序应用 appid
    public $component_appid = "";
    // 第三方小程序应用 APPSecret
    public $component_appsecret = "";
    // 第三方小程序应用接口调用凭据
    // 消息验证 TOKEN
    public $token = "";
    // 消息加密解密 KEY
    public $key = "";

    public $err = '';

    public function __construct($config)
    {
        if (empty($config['component_appid'])) {
            throw new \Exception('not empty component_appid');
        }
        if (empty($config['component_appsecret'])) {
            throw new \Exception('not empty component_appsecret');
        }
        if (empty($config['token'])) {
            throw new \Exception('not empty token');
        }
        if (empty($config['key'])) {
            throw new \Exception('not empty key');
        }
        $this->component_appid = $config['component_appid'];
        $this->component_appsecret = $config['component_appsecret'];
        $this->token = $config['token'];
        $this->key = $config['key'];
    }


    /**
     * 获取推送的component_ticket
     * @doc https://partner.open-douyin.com/docs/resource/zh-CN/thirdparty/API/smallprogram/authorization/componentticket
     * @param $Encrypt
     * @return false|mixed
     */
    public function getComponentTicket($Encrypt)
    {
        try {
            $Aes = new AesEncryptUtil($this->key);
            $res = $Aes->decrypt($Encrypt);
            return json_decode($res, true)['Ticket'];
        } catch (\Exception $e) {
            $this->err = $e->getMessage();
            return false;
        }
    }

    /**
     * 解密
     */
    public function getEventDecrypt($Encrypt)
    {
        try {
            $Aes = new AesEncryptUtil($this->key);
            $res = $Aes->decrypt($Encrypt);
            return json_decode($res, true);
        } catch (\Exception $e) {
            $this->err = $e->getMessage();
            return false;
        }
    }

    /**
     * 获取第三方小程序接口调用凭据
     * @doc https://partner.open-douyin.com/docs/resource/zh-CN/thirdparty/API/smallprogram/authorization/componentaccesstoken
     * @param $component_ticket
     * @return false|mixed
     */
    public function getComponentAccessToken($component_ticket)
    {
        $params = http_build_query([
            'component_appid'     => $this->component_appid,
            'component_appsecret' => $this->component_appsecret,
            'component_ticket'    => $component_ticket
        ]);
        $url = 'https://open.microapp.bytedance.com/openapi/v1/auth/tp/token?' . $params;
        $res = json_decode(httpGet($url), true);
        return $res;
    }


    /**
     * 获取第三方小程序接口调用凭据
     * @doc https://partner.open-douyin.com/docs/resource/zh-CN/thirdparty/API/smallprogram/authorization/componentaccesstoken
     * @param $component_ticket
     * @return false|mixed
     */
    public function getComponentAccessTokenV2($component_ticket)
    {
        $params = http_build_query([
            'component_appid'     => $this->component_appid,
            'component_appsecret' => $this->component_appsecret,
            'component_ticket'    => $component_ticket
        ]);
        $url = 'https://open.douyin.com/openapi/v2/auth/tp/token/?' . $params;
        return $this->httpGet($url);
    }

    /**
     * 直接获取授权链接
     * @doc https://partner.open-douyin.com/docs/resource/zh-CN/thirdparty/API/smallprogram/authorization/genlink
     * @param $component_access_token
     * @param $data
     * @return mixed
     */
    public function getGenLink($component_access_token, $appid, $data = ['link_type' => 1])
    {
        $params = http_build_query([
            'component_appid'        => $this->component_appid,
            'component_access_token' => $component_access_token,
        ]);
        // 回调地址
        $data['redirect_uri'] = request()->domain() . '/dy/open/call_back?appid=' . $appid;
        $url = 'https://open.microapp.bytedance.com/openapi/v2/auth/gen_link?' . $params;
        $res = $this->httpPost($url, $data);
        return $res;
    }


    /**
     * 获取授权小程序接口调用凭据
     * @doc https://partner.open-douyin.com/docs/resource/zh-CN/thirdparty/API/smallprogram/authorization/authorizeraccesstoken
     * @param $component_access_token
     * @param $authorization_code
     * @return mixed
     */
    public function getAuthorizerAccessToken($component_access_token, $authorization_code)
    {
        $params = http_build_query([
            'component_appid'        => $this->component_appid,
            'component_access_token' => $component_access_token,
            'authorization_code'     => $authorization_code,
            'grant_type'             => 'app_to_tp_authorization_code'// 固定
        ]);
        $url = "https://open.microapp.bytedance.com/openapi/v1/oauth/token?" . $params;

        $res = httpGet($url);
        $res = json_decode($res, true);
        return $res;
    }

    /**
     * 获取授权小程序接口调用凭据 V2
     * @doc https://partner.open-douyin.com/docs/resource/zh-CN/thirdparty/API/smallprogram/authorization/authorizeraccesstoken-v2
     * @param $component_access_token
     * @param $authorization_code
     * @return mixed
     */
    public function getAuthorizerAccessToken_V2($component_access_token, $authorization_code)
    {
        $params = http_build_query([
            'authorization_code' => $authorization_code,
            'grant_type'         => 'app_to_tp_authorization_code'// 固定
        ]);
        $url = "https://open.douyin.com/api/tpapp/v2/auth/get_auth_token/?" . $params;
        $res = $this->httpGet($url, [
            'access-token' => $component_access_token
        ]);
        return $res;
    }

    /**
     * 刷新授权小程序接口调用凭据
     * @doc https://partner.open-douyin.com/docs/resource/zh-CN/thirdparty/API/smallprogram/authorization/authorizerrefreshtoken
     * @param $component_access_token string 第三方小程序应用接口调用凭据
     * @param $authorizer_refresh_token string 刷新令牌
     * @return mixed
     */
    public function refreshAuthorizerAccessToken($component_access_token, $authorizer_refresh_token)
    {
        $params = http_build_query([
            'component_appid'          => $this->component_appid,
            'component_access_token'   => $component_access_token,
            'authorizer_refresh_token' => $authorizer_refresh_token,
            'grant_type'               => 'app_to_tp_refresh_token'// 固定
        ]);
        $url = "https://open.microapp.bytedance.com/openapi/v1/oauth/token?" . $params;

        $res = httpGet($url);
        $res = json_decode($res, true);
        return $res;
    }

    /**
     * 刷新授权小程序接口调用凭据V2
     * @doc https://partner.open-douyin.com/docs/resource/zh-CN/thirdparty/API/smallprogram/authorization/authorizerrefreshtoken-v2
     * @param $component_access_token
     * @param $authorizer_refresh_token
     * @return mixed
     */
    public function refreshAuthorizerAccessToken_V2($component_access_token, $authorizer_refresh_token)
    {
        $params = http_build_query([
            'authorizer_refresh_token' => $authorizer_refresh_token,
            'grant_type'               => 'app_to_tp_refresh_token'// 固定
        ]);
        $url = "https://open.douyin.com/api/tpapp/v2/auth/get_auth_token/?" . $params;
        $res = $this->httpGet($url, [
            'access-token' => $component_access_token
        ]);
        return $res;
    }


    /**
     * 找回授权码
     * @doc https://partner.open-douyin.com/docs/resource/zh-CN/thirdparty/API/smallprogram/authorization/findauthorizationcode
     * @param $component_access_token
     * @param $authorization_appid
     * @return array ['authorization_code','expires_in']
     */
    public function retrieveAuthorizationCode($component_access_token, $authorization_appid)
    {
        $params = http_build_query([
            'component_appid'        => $this->component_appid,
            'component_access_token' => $component_access_token,
            'authorization_appid'    => $authorization_appid,
        ]);
        $url = "https://open.microapp.bytedance.com/openapi/v1/auth/retrieve?" . $params;
        $res = $this->httpPost($url, []);
        return $res;
    }

    /**
     * 找回授权码 V2
     * @doc https://partner.open-douyin.com/docs/resource/zh-CN/thirdparty/API/smallprogram/authorization/findauthorizationcode
     * @param $component_access_token
     * @param $authorization_appid
     * @return array ['authorization_code','expires_in']
     */
    public function retrieveAuthorizationCode_V2($component_access_token, $authorization_appid)
    {
        $data = ['authorization_appid' => $authorization_appid];
        $url = "https://open.douyin.com/api/tpapp/v2/auth/retrieve_auth_code/";
        $res = $this->httpPost($url, $data, [
            'access-token' => $component_access_token
        ]);
        return $res;
    }


    /**
     * 提交代码
     * @doc https://partner.open-douyin.com/docs/resource/zh-CN/thirdparty/API/smallprogram/auth-app-manage/develop/upload-code
     * @param $authorizer_access_token
     * @param $data array ['template_id','user_desc','user_version','ext_json']
     * @param $authorizer_access_token
     * @param $data
     * @return mixed
     */
    public function upload($authorizer_access_token, $data)
    {
        $url = "https://open.microapp.bytedance.com/openapi/v1/microapp/package/upload?" . http_build_query([
                'component_appid'         => $this->component_appid,
                'authorizer_access_token' => $authorizer_access_token
            ]);
        $res = $this->httpPost($url, $data);
        return $res;
    }

    /**
     * 提审代码
     * @doc https://partner.open-douyin.com/docs/resource/zh-CN/thirdparty/API/smallprogram/auth-app-manage/develop/audit-code
     * @param $authorizer_access_token
     * @param $data
     * @return mixed
     */
    public function audit($authorizer_access_token, $data)
    {
        $url = "https://open.microapp.bytedance.com/openapi/v2/microapp/package/audit?" . http_build_query([
                'component_appid'         => $this->component_appid,
                'authorizer_access_token' => $authorizer_access_token
            ]);
        $res = $this->httpPost($url, $data);
        return $res;
    }

    /**
     * 发布代码
     * @doc https://partner.open-douyin.com/docs/resource/zh-CN/thirdparty/API/smallprogram/auth-app-manage/develop/release
     * @param $authorizer_access_token
     * @param $data
     * @return mixed
     */
    public function release($authorizer_access_token)
    {
        $url = "https://open.microapp.bytedance.com/openapi/v1/microapp/package/release?" . http_build_query([
                'component_appid'         => $this->component_appid,
                'authorizer_access_token' => $authorizer_access_token
            ]);
        $res = $this->httpPost($url, []);
        return $res;
    }

    /**
     * 撤回审核
     * @doc https://partner.open-douyin.com/docs/resource/zh-CN/thirdparty/API/smallprogram/auth-app-manage/develop/revoke-audit
     * @param $authorizer_access_token
     * @return mixed
     */
    public function revoke_audit($authorizer_access_token)
    {
        $url = "https://open.microapp.bytedance.com/openapi/v1/microapp/package/revoke_audit?" . http_build_query([
                'component_appid'         => $this->component_appid,
                'authorizer_access_token' => $authorizer_access_token
            ]);
        $res = $this->httpPost($url, []);
        return $res;
    }

    /**
     * 获取可选审核宿主端列表
     * @doc https://partner.open-douyin.com/docs/resource/zh-CN/thirdparty/API/smallprogram/auth-app-manage/develop/audit-hosts
     * @param $authorizer_access_token
     * @return mixed
     */
    public function get_audit_hosts($authorizer_access_token)
    {
        $url = "https://open.microapp.bytedance.com/openapi/v1/microapp/package/audit_hosts?" . http_build_query([
                'component_appid'         => $this->component_appid,
                'authorizer_access_token' => $authorizer_access_token
            ]);
        $res = httpGet($url);
        return $res;
    }

    /**
     * 获取小程序版本列表信息
     * @doc https://partner.open-douyin.com/docs/resource/zh-CN/thirdparty/API/smallprogram/auth-app-manage/develop/versions
     * @param $authorizer_access_token
     * @return mixed
     */
    public function versions($authorizer_access_token)
    {
        $url = "https://open.microapp.bytedance.com/openapi/v1/microapp/package/versions?" . http_build_query([
                'component_appid'         => $this->component_appid,
                'authorizer_access_token' => $authorizer_access_token
            ]);
        $res = $this->httpGet($url);
        return $res;
    }

    /**
     * 获取二维码
     * @doc https://partner.open-douyin.com/docs/resource/zh-CN/thirdparty/API/smallprogram/auth-app-manage/base-info/qrcode-v2
     * @param $authorizer_access_token
     * @param $version string 版本阶段： current 或 audit 或 latest; current 线上版; audit 审核版; latest 测试版
     * @param $path string 启动参数，包含两部分: 页面路径?页面参数
     * @return mixed
     */
    public function getQrcode($authorizer_access_token, $version, $path = '')
    {
        $url = "https://open.microapp.bytedance.com/openapi/v1/microapp/app/qrcode?" . http_build_query([
                'component_appid'         => $this->component_appid,
                'authorizer_access_token' => $authorizer_access_token
            ]);
        $res = httpPost($url, [
            'version' => $version,
            'path'    => $path
        ], true);
        return $res;
    }

    /**
     * 服务商登录
     * @doc https://partner.open-douyin.com/docs/resource/zh-CN/thirdparty/API/smallprogram/auth-app-manage/login/code2session
     * Create by :  刘泓宾<514660094@qq.com>
     * @param $authorizer_access_token
     * @param $code
     * @param $anonymous_code
     * @return mixed
     */
    public function login($authorizer_access_token, $code, $anonymous_code = '')
    {
        $query = [
            'component_appid'         => $this->component_appid,
            'authorizer_access_token' => $authorizer_access_token,
            'code'                    => $code,
        ];
        if ($anonymous_code) {
            $query['anonymous_code'] = $anonymous_code;
        }
        $url = "https://open.microapp.bytedance.com/openapi/v1/microapp/code2session?" . http_build_query($query);
        $res = $this->httpGet($url);
        return $res;
    }

    /**
     * 获取小程序基本信息
     * @doc https://partner.open-douyin.com/docs/resource/zh-CN/thirdparty/API/smallprogram/auth-app-manage/base-info/info
     * Create by :  刘泓宾<514660094@qq.com>
     * @param $authorizer_access_token
     * @return mixed
     */
    public function info($authorizer_access_token)
    {
        $query = [
            'component_appid'         => $this->component_appid,
            'authorizer_access_token' => $authorizer_access_token
        ];
        $url = "https://open.microapp.bytedance.com/openapi/v1/microapp/app/info?" . http_build_query($query);
        return $this->httpGet($url);
    }
}
